<template>
  <view class="container">
    <!-- 登录提示条 -->
    <view class="login-tip" v-if="!hasToken">
      <text>登录后可查看更多精彩内容</text>
      <button class="login-btn" @click="goLogin">去登录</button>
    </view>

    <!-- 顶部操作栏 -->
    <view class="header">
      <text class="title">照片圈</text>
      <view class="upload-btn" @click="handleAction('upload')">
        <uni-icons type="camera-filled" size="24" color="#3a8838"></uni-icons>
      </view>
    </view>

    <!-- 照片列表 -->
    <scroll-view 
      class="photo-list-container"
      scroll-y
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <template v-if="hasToken">
        <!-- 加载中 -->
        <view v-if="loading.photos" class="loading-container">
          <u-loading-icon size="24" color="#3a8838"></u-loading-icon>
          <text>加载中...</text>
        </view>
        
        <!-- 加载错误 -->
        <view v-else-if="loading.error" class="error-container">
          <text>{{loading.error}}</text>
          <button class="retry-btn" @click="loadData">重试</button>
        </view>
        
        <!-- 照片列表 -->
        <template v-else-if="photos.length">
          <view class="photo-list">
            <view class="photo-item" v-for="photo in photoList" :key="photo.photoId">
              <!-- 照片信息 -->
              <view class="photo-header">
                <view class="author-info">
                  <image :src="photo.avatarUrl" class="avatar" mode="aspectFill"></image>
                  <text class="author-name">{{photo.nickName}}</text>
                </view>
              </view>

              <!-- 照片内容 -->
              <view class="photo-content" @click="handleAction('photoSelect', photo)">
                <image :src="photo.url" mode="widthFix" class="photo-image"></image>
                <view class="photo-text" v-if="photo.title || photo.description">
                  <view class="title-row">
                    <text class="photo-title" v-if="photo.title">{{photo.title}}</text>
                    <view class="like-btn" @click.stop="handleAction('like', photo)">
                      <u-icon 
                        :name="photo.likedByCurrentUser ? 'heart-fill' : 'heart'" 
                        size="20" 
                        :class="{'like-icon': true, 'liked': photo.likedByCurrentUser}"
                        :color="photo.likedByCurrentUser ? '#ff5a5f' : '#666'"
                      ></u-icon>
                      <text :class="{'active': photo.likedByCurrentUser}">{{photo.likeCount || 0}}</text>
                    </view>
                  </view>
                  <text class="photo-desc" v-if="photo.description">{{photo.description}}</text>
                </view>
              </view>

              <!-- 操作栏 -->
              <view class="photo-actions">
                <view class="action-left">
                  <view class="action-item" @click.stop="handleAction('comment', photo)">
                    <u-icon type="chatbubble" size="20" color="#666"></u-icon>
                  </view>
                </view>
                <view class="action-right">
                  <view class="action-item" @click.stop="handleAction('share', photo)">
                    <u-icon type="share" size="20" color="#666"></u-icon>
                  </view>
                </view>
              </view>

              <!-- 评论预览 -->
              <view class="comment-preview" v-if="photo.comments && photo.comments.length">
                <view class="comment-item" v-for="comment in photo.comments" :key="comment.commentId">
                  <text class="comment-user">{{comment.userNickname}}</text>
                  <text class="comment-content">{{comment.content}}</text>
                </view>
                <view class="comment-more" v-if="photo.commentCount > 2" @click.stop="handleAction('comment', photo)">
                  查看全部 {{photo.commentCount}} 条评论
                </view>
              </view>
            </view>
          </view>

          <!-- 加载更多 -->
          <view class="loading-more" v-if="isLoading">
            <u-loading-icon size="24" color="#999"></u-loading-icon>
            <text>加载中...</text>
          </view>

          <!-- 没有更多数据 -->
          <view class="no-more" v-if="noMoreData && photos.length">
            <text>没有更多照片了</text>
          </view>
        </template>
        
        <!-- 空状态 -->
        <view v-else class="empty-tip">
          <text>暂无照片</text>
        </view>
      </template>
      
      <!-- 未登录状态 -->
      <view v-else class="empty-tip">
        <text>登录后查看照片</text>
      </view>
    </scroll-view>

    <tab-bar :tabIndex="1"></tab-bar>
  </view>
</template>

<script>
import TabBar from '@/components/tab-bar/tab-bar.vue'
import { getPhotoComments, likePhoto, unlikePhoto } from '@/api/photo'
import { getImageBlob, getAvatarUrl } from '@/utils/image.js'

export default {
  components: {
    TabBar
  },
  data() {
    return {
      hasToken: false,
      photos: [],
      page: 1,
      pageSize: 10,
      isLoading: false,
      noMoreData: false,
      isRefreshing: false,
      isReady: false,
      loading: {
        photos: false,
        error: null
      },
      scrollTop: 0,
      needRefresh: false
    }
  },
  computed: {
    photoList() {
      console.log('photoList computed 输入:', this.photos)
      const processed = this.photos.map(photo => {
        // 处理评论数据
        const comments = photo.comment || []
        const previewComments = comments.slice(0, 2).map(comment => {
          if (!comment) return null
          try {
            const parsed = typeof comment.content === 'string' ? JSON.parse(comment.content) : comment.content
            return {
              ...comment,
              content: parsed.content || comment.content
            }
          } catch (e) {
            console.warn('解析评论内容失败:', e, comment)
            return {
              ...comment,
              content: comment.content
            }
          }
        }).filter(Boolean)

        const processed = {
          ...photo,
          comments: previewComments,
          commentCount: comments.length,
          likeCount: parseInt(photo.likeCount) || 0,
          likedByCurrentUser: photo.likedByCurrentUser || false
        }
        return processed
      })
      console.log('photoList computed 输出:', processed)
      return processed
    }
  },
  onLoad() {
    this.checkToken()
  },
  onReady() {
    setTimeout(() => {
      this.isReady = true
      if (this.hasToken && !this.photos.length) {
        this.loadData()
      }
    }, 300)
  },
  onShow() {
    if (!this.isReady) return
    this.checkToken()
    if (this.hasToken && this.needRefresh) {
      this.loadData()
      this.needRefresh = false
    }
  },
  onHide() {
    const query = uni.createSelectorQuery().in(this)
    query.select('.photo-list-container').scrollOffset((data) => {
      if (data) {
        this.scrollTop = data.scrollTop
      }
    }).exec()
  },
  onReachBottom() {
    if (!this.isLoading && !this.noMoreData) {
      this.loadMore()
    }
  },
  methods: {
    checkToken() {
      try {
        const token = uni.getStorageSync('token')
        this.hasToken = !!token
      } catch (err) {
        console.error('检查token失败:', err)
        this.hasToken = false
      }
    },
    async loadData() {
      if (this.isLoading) return
      
      this.isLoading = true
      this.loading.photos = true
      this.loading.error = null
      
      try {
        const params = {
          current: 1,
          size: this.pageSize
        }
        const result = await getPhotoComments(params)
        console.log('接口返回数据:', result)
        
        if (!result || !result.data) {
          throw new Error('返回数据格式错误')
        }
        
        const photos = result.data.records || []
        console.log('解析后的照片数据:', photos)
        
        if (photos.length === 0) {
          console.log('没有照片数据')
          this.photos = []
          this.noMoreData = true
          return
        }
        
        // 使用Promise.all优化图片加载
        const processedPhotos = await Promise.all(photos.map(async (photo) => {
          try {
            const [url, avatarUrl] = await Promise.all([
              getImageBlob(photo.photoPath),
              getAvatarUrl(photo.avatar)
            ])
            return {
              ...photo,
              url,
              avatarUrl,
              likedByCurrentUser: photo.likedByCurrentUser || false,
              likeCount: parseInt(photo.likeCount) || 0,
              comment: photo.comment || []
            }
          } catch (err) {
            console.error('加载图片失败:', err, photo)
            return {
              ...photo,
              url: '',
              avatarUrl: '',
              likedByCurrentUser: photo.likedByCurrentUser || false,
              likeCount: parseInt(photo.likeCount) || 0,
              comment: photo.comment || []
            }
          }
        }))
        
        console.log('处理后的照片数据:', processedPhotos)
        this.photos = processedPhotos
        this.noMoreData = photos.length < this.pageSize
        this.page = 1

        if (this.scrollTop > 0) {
          setTimeout(() => {
            uni.pageScrollTo({
              scrollTop: this.scrollTop,
              duration: 0
            })
          }, 100)
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.loading.error = error.message || '加载失败'
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
        this.isRefreshing = false
        this.loading.photos = false
      }
    },
    async loadMore() {
      if (this.isLoading || this.noMoreData || !this.isReady) return
      
      this.isLoading = true
      try {
        const params = {
          current: this.page + 1,
          size: this.pageSize
        }
        const result = await getPhotoComments(params)
        if (!result || !result.data) {
          throw new Error('返回数据格式错误')
        }
        
        const photos = result.data.records || []
        
        // 使用Promise.all优化图片加载
        await Promise.all(photos.map(async (photo) => {
          try {
            const [url, avatarUrl] = await Promise.all([
              getImageBlob(photo.photoPath),
              getAvatarUrl(photo.avatar)
            ])
            photo.url = url
            photo.avatarUrl = avatarUrl
          } catch (err) {
            console.error('加载图片失败:', err)
            photo.url = ''
            photo.avatarUrl = ''
          }
        }))
        
        this.photos.push(...photos)
        this.noMoreData = photos.length < this.pageSize
        this.page++
      } catch (error) {
        console.error('加载更多失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
      }
    },
    goLogin() {
      uni.navigateTo({
        url: '/pages/login/login'
      })
    },
    async handleAction(type, data) {
      if (!this.hasToken) {
        uni.navigateTo({
          url: '/pages/login/login'
        })
        return
      }
      
      switch (type) {
        case 'upload':
          uni.navigateTo({
            url: '/pages/photo/upload'
          })
          break
        case 'photoSelect':
          uni.navigateTo({
            url: `/pages/photo/detail?id=${data.photoId}`
          })
          break
        case 'like':
          try {
            await this.handleLike(data)
          } catch (err) {
            console.error('点赞失败:', err)
            uni.showToast({
              title: '操作失败',
              icon: 'none'
            })
          }
          break
        case 'comment':
          uni.navigateTo({
            url: `/pages/photo/detail?id=${data.photoId}&showComment=1`
          })
          break
        case 'share':
          uni.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
          })
          break
      }
    },
    async handleLike(photo) {
      try {
        const index = this.photos.findIndex(p => p.photoId === photo.photoId)
        if (index === -1) return

        if (photo.likedByCurrentUser) {
          // 取消点赞
          await unlikePhoto(photo.photoId)
          this.$set(this.photos[index], 'likedByCurrentUser', false)
          this.$set(this.photos[index], 'likeCount', Math.max(0, photo.likeCount - 1))
        } else {
          // 点赞
          await likePhoto(photo.photoId)
          this.$set(this.photos[index], 'likedByCurrentUser', true)
          this.$set(this.photos[index], 'likeCount', (photo.likeCount || 0) + 1)
        }
        // 标记需要刷新，但不立即刷新
        this.needRefresh = true
      } catch (error) {
        console.error('点赞操作失败:', error)
        uni.showToast({
          title: '操作失败，请重试',
          icon: 'none'
        })
      }
    },
    onRefresh() {
      this.isRefreshing = true
      this.loadData()
    }
  }
}
</script>

<style>
.container {
  position: relative;
  min-height: 100vh;
  background-color: #f8f8f8;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 88rpx;
  box-sizing: border-box;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.upload-btn {
  padding: 10rpx;
}

.topics-scroll,
.topics-list,
.topic-item,
.topic-name,
.topic-count {
  display: none;
}

.photo-list-container {
  height: calc(100vh - 88rpx);
  padding-top: 88rpx;
}

.photo-list {
  padding: 0;
}

.photo-item {
  background-color: #fff;
  padding: 20rpx 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  border-radius: 0;
}

.photo-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.author-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 70rpx;
  height: 70rpx;
  border-radius: 50%;
  margin-right: 15rpx;
}

.author-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.photo-stats {
  display: flex;
  align-items: center;
  margin-left: 20rpx;
  background: rgba(0,0,0,0.02);
  border-radius: 30rpx;
  padding: 4rpx 10rpx;
}

.stat-item {
  display: flex;
  align-items: center;
  margin-left: 20rpx;
  padding: 4rpx 8rpx;
}

.stat-item:first-child {
  margin-left: 0;
}

.stat-item text {
  font-size: 24rpx;
  color: #666;
  margin-left: 6rpx;
  min-width: 20rpx;
  text-align: center;
}

.photo-content {
  margin-bottom: 0;
}

.photo-image {
  width: 100%;
  border-radius: 8rpx;
  margin-bottom: 12rpx;
}

.photo-text {
  padding: 15rpx 0;
}

.title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

.photo-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
  margin-right: 15rpx;
}

.photo-desc {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
  display: block;
  margin-top: 8rpx;
}

.photo-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 10rpx;
  border-top: 1px solid #f5f5f5;
  margin-top: 15rpx;
}

.action-left {
  display: flex;
  align-items: center;
}

.action-item {
  display: flex;
  align-items: center;
  padding: 8rpx 15rpx;
  margin-right: 20rpx;
  border-radius: 30rpx;
  background: rgba(0,0,0,0.02);
  transition: all 0.3s ease;
}

.action-item:active {
  background: rgba(0,0,0,0.05);
  transform: scale(0.92);
}

.action-item text {
  font-size: 26rpx;
  color: #666;
  margin-left: 8rpx;
  transition: all 0.3s ease;
}

.action-item text.active {
  color: #ff5a5f;
  font-weight: 500;
}

.action-right {
  display: flex;
  align-items: center;
}

.comment-preview {
  margin-top: 15rpx;
  padding: 15rpx;
  background: rgba(0,0,0,0.02);
  border-radius: 12rpx;
}

.comment-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12rpx;
}

.comment-user {
  font-size: 26rpx;
  color: #3a8838;
  font-weight: bold;
  margin-right: 10rpx;
  flex-shrink: 0;
}

.comment-content {
  font-size: 26rpx;
  color: #333;
  line-height: 1.4;
  flex: 1;
}

.comment-more {
  font-size: 24rpx;
  color: #666;
  text-align: center;
  padding: 10rpx 0 0;
  border-top: 1px solid rgba(0,0,0,0.05);
  margin-top: 10rpx;
}

.comment-more:active {
  opacity: 0.8;
}

.loading-more, .no-more {
  text-align: center;
  padding: 40rpx 0 60rpx;
  color: #999;
  font-size: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-more .u-loading-icon {
  margin-right: 10rpx;
}

.login-tip {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 101;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 30rpx;
  background-color: rgba(58, 136, 56, 0.1);
  border-bottom: 1rpx solid rgba(58, 136, 56, 0.2);
}

.login-tip text {
  font-size: 26rpx;
  color: #3a8838;
}

.login-tip .login-btn {
  background: #3a8838;
  color: #fff;
  font-size: 24rpx;
  padding: 8rpx 30rpx;
  border-radius: 30rpx;
  margin: 0;
  line-height: 1.5;
}

.login-btn::after {
  border: none;
}

.empty-tip {
  text-align: center;
  padding: 100rpx 30rpx;
  color: #999;
  font-size: 28rpx;
  background: #f8f8f8;
  margin: 0;
  border-radius: 0;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.loading-container text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #999;
}

.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.error-container text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 20rpx;
}

.retry-btn {
  background: #3a8838;
  color: #fff;
  font-size: 28rpx;
  padding: 10rpx 40rpx;
  border-radius: 30rpx;
  margin: 0;
  line-height: 1.5;
}

.retry-btn::after {
  border: none;
}

.like-btn {
  display: flex;
  align-items: center;
  padding: 8rpx 15rpx;
  border-radius: 30rpx;
  background: rgba(0,0,0,0.02);
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.like-btn:active {
  background: rgba(0,0,0,0.05);
  transform: scale(0.92);
}

.like-btn text {
  font-size: 26rpx;
  color: #666;
  margin-left: 8rpx;
  transition: all 0.3s ease;
}

.like-btn text.active {
  color: #ff5a5f;
  font-weight: 500;
}

.like-icon {
  transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

.like-btn:active .like-icon {
  transform: scale(0.8);
}

.like-btn:active .like-icon.liked {
  transform: scale(1);
}

.like-icon.liked {
  transform: scale(1.2);
}
</style> 